<script setup>
import {ElContainer, ElMain, ElDialog, ElMessageBox} from 'element-plus';
import Head from '../components/head.vue'
import asider from '../components/aside.vue'
import { ref,onMounted } from 'vue'
import axios from "axios";
import router from "../router";
const input = ref('')
const tableData = ref([])
//存储初次加载的所有数据
const initialData=ref([])
//接收多选框选中的数据
const selectedRows = ref([]);
//保存选中的数据
const handleSelection = (val) => {
  selectedRows.value = val;
};
//页面加载时查询所有信息
onMounted(async ()=>{
  //判断是否有人登录
  let data=sessionStorage.getItem('manager');
  if(data==null){//未登录就通过路径跳转直接送回登录页面
    alert("不买票就想上车？不登录你就想搞事？");
    router.push('/')
  }else{
    //axios方法与后端一致
    const response = await axios.get('/building/').then(result=>{
      if(result.data.message=="查询成功"){
        tableData.value = result.data.data
        initialData.value=result.data.data
      }else {
        alert(result.data.message);
      }
    }).catch(error=>{
      alert('请求出现问题，请稍后再试'+error);
    })
  }
})
//输入框查询
const Query = async ()=>{
  //axios方法与后端一致，@Requestparam的参数使用“params:{}”传递
  const response = await axios.get('/building/select',{params:{name:input.value}})
      .then(result=>{
        if(!input.value){
          alert("请输入查询内容");
          return;
        }
        if(result.data.message=="查询成功"){
          tableData.value = result.data.data
        }else {
          alert(result.data.message);
        }
      }).catch(error=>{
        alert('请求出现问题，请稍后再试'+error);
      })
}
//弹出框显示隐藏的名称
const nameVisible = ref(false);
//弹出框显示隐藏的简介
const introductionVisible = ref(false);
//存储正在编辑的名字的响应式数据
const editingName = ref(null);
//存储正在编辑的内容的响应式数据
const editingIntroduction = ref(null);
//存储当前正在编辑的行，方便后续更新操作定位到具体行
const currentRow = ref({});
//点击表格列文本内容弹出修改框
const Editname = (event, row) => {
  nameVisible.value = true;
  editingName.value = row.name; //设置编辑框初始值
  currentRow.value = row;
};
const Editintroduction = (event, row) => {
  introductionVisible.value = true;
  editingIntroduction.value = row.introduction; //设置编辑框初始值
  currentRow.value = row;
};
//保存修改内容
const Update=async ()=>{
  try{
    //修改名字
    if(editingName.value){
      //axios方法与后端一致,非get方法后端使用@Requestbody接收数据
      const response = await axios({url:'/building/update', method:'put',data:{id:currentRow.value.id,name:editingName.value,introduction:editingIntroduction.value}})
          .then(result=> {
            if (result.data.message.includes("修改成功")) {
              alert(result.data.message);
            }else {
              alert(result.data.message);
            }
          }).catch(error => {
            alert('请求出现问题，请稍后再试' + error);
          })
    }else {
      //修改简介
      const response=await axios({url:'/building/update',method:'put',data:{id:currentRow.value.id,name:editingName.value,introduction:editingIntroduction.value}})
          .then(result=>{
            if(result.data.message.includes("修改成功")){
              alert(result.data.message);
            }else {
              alert(result.data.message);
            }
          }).catch(error => {
            alert('请求出现问题，请稍后再试' + error);
          })
    }
  }finally {
    Close();
  }
}
//处理修改框关闭前的事件
const Close = () => {
  addVisible.value = false;
  nameVisible.value = false;
  introductionVisible.value = false;
  editingName.value = null;
  editingIntroduction.value = null;
  currentRow.value = null;
};
const addVisible = ref(false);
//添加信息
const Add=async ()=>{
  addVisible.value = true;
}
const Upload=async ()=>{
  try{
    //axios方法与后端一致,非get方法后端使用@Requestbody接收数据
    const response = await axios({url:'/building/upload', method:'post',data:{name:editingName.value,introduction:editingIntroduction.value}})
        .then(result=>{
          if(result.data.message.includes("添加成功")){
            alert(result.data.message);
          }else {
            alert(result.data.message);
          }
        })
  }catch(error){
      alert('请求出现问题，请稍后再试'+error);
  }finally {
    Close();
  }
}
//删除所选内容
const Delete = async ()=> {
  try{
    if (selectedRows.value.length == 0) {
      alert("请选择要删除的账号");
      return;
    }
    //弹消息框确认删除
    const confirm = await ElMessageBox.confirm('确认删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true
    }).then(async () => {
      //提取需要的数据
      const idlist = selectedRows.value.map((row) => row.id)
      //axios方法与后端一致,非get方法后端使用@Requestbody接收数据
      const response = await axios({url: '/building/delete', method: 'delete', data: idlist})
          .then(result => {
            if (result.data.message.includes("删除成功")) {
              alert(result.data.message);
            } else {
              alert(result.data.message);
            }
          }).catch(error => {
            alert('请求出现问题，请稍后再试' + error);
          })
    })
  }catch (error) {
    alert(error);
  }
}
//输入框为空时，恢复初始数据
const inputChange = () => {
  if (!input.value){
    tableData.value = initialData.value;
  }
};
</script>
<template>
  <div class="common-layout" style="text-align: center;">
    <Head></Head>
    <el-container style="height: 80vh">
      <asider></asider>
      <el-main >
        <el-button type="success" style="float: left" @click="Add">添加</el-button>
        <el-button type="danger" style="float: left" @click="Delete">删除</el-button>
        <el-dialog v-model="addVisible" title="新增" :before-close="Close" draggable>
          <el-form-item label="名称">
            <el-input  v-model="editingName" autosize type="textarea" placeholder="请输入要添加的内容" />
          </el-form-item>
          <el-form-item label="简介">
            <el-input  v-model="editingIntroduction" autosize type="textarea" placeholder="请输入要添加的内容" />
          </el-form-item>
          <template #footer >
        <span class="dialog-footer">
          <el-button @click="Close">取消</el-button>
          <el-button type="primary" @click="Upload">添加</el-button>
        </span>
          </template>
        </el-dialog>
        <el-form @keydown.enter="Query" @submit.prevent>
          <el-button type="primary" style="float: right" @click="Query">查询</el-button>
          <el-input v-model="input" style="width: 240px;float: right"
                    placeholder="输入名称进行查询" clearable @input="inputChange"/>
        </el-form>
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelection" >
          <!--多选框-->
          <el-table-column type="selection" width="80" prop="id"/>
          <el-table-column label="建筑名称" prop="name" width="400" header-align="center" align="center" >
            <template v-slot="scope">
              <span @click="Editname($event, scope.row)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="简介" prop="introduction" width="700" header-align="center" align="center" show-overflow-tooltip>
            <template v-slot="scope">
              <span @click="Editintroduction($event, scope.row)">{{ scope.row.introduction }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- 使用ElDialog组件实现弹出框修改名字 -->
        <el-dialog v-model="nameVisible" title="编辑名称" :before-close="Close" draggable>
          <el-input v-model="editingName" autosize type="textarea" placeholder="请输入修改后的内容" />
          <template #footer >
        <span class="dialog-footer">
          <el-button @click="Close">取消</el-button>
          <el-button type="primary" @click="Update">修改</el-button>
        </span>
          </template>
        </el-dialog>
        <!-- 使用ElDialog组件实现弹出框修改内容 -->
        <el-dialog v-model="introductionVisible" title="编辑简介" :before-close="Close" draggable>
          <el-input v-model="editingIntroduction" autosize type="textarea" placeholder="请输入修改后的内容" />
          <template #footer >
        <span class="dialog-footer">
          <el-button @click="Close">取消</el-button>
          <el-button type="primary" @click="Update">修改</el-button>
        </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<style>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
